package com.LC.Controller.User;


import com.LC.Constant.MessageConstant;
import com.LC.Entity.*;
import com.LC.Service.UserService;
import com.LC.Utils.DateUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {
    
    @Reference
    UserService userService;
    
    @Autowired
    BCryptPasswordEncoder passwordEncoder;
    
    @PreAuthorize("hasAuthority('USER_ADD')")
    @PostMapping("/User/{RoleIds}")
    public Result AddUser(@PathVariable Integer[] RoleIds, @RequestBody com.LC.Entity.User AddUser){
        try {
            String OriginalPassword = AddUser.getPassword();
            AddUser.setPassword(passwordEncoder.encode(OriginalPassword));
            userService.AddUser(RoleIds,AddUser);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_USER_FAIL);
        }
        return new Result(true,MessageConstant.ADD_USER_SUCCESS);
    }
    
    @PreAuthorize("hasAuthority('USER_EDIT')")
    @PutMapping("/User")
    public Result EditUser(@RequestBody UserPUT userPUT){
        try {
            String DBPassword = userService.GetUserById(userPUT.getUpdateUser().getId()).getPassword();
            if (!DBPassword.equals(userPUT.getUpdateUser().getPassword())){
                String NewPassword = userPUT.getUpdateUser().getPassword();
                userPUT.getUpdateUser().setPassword(passwordEncoder.encode(NewPassword));
            }
            userService.EditUser(userPUT.getRoleIds(), userPUT.getUpdateUser());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_USER_FAIL);
        }
        return new Result(true,MessageConstant.EDIT_USER_SUCCESS);
    }
    
    @PreAuthorize("hasAuthority('USER_QUERY')")
    @GetMapping("/User/{id}")
    public Result GetUserById(@PathVariable int id){
        com.LC.Entity.User userById = null;
        try {
            userById = userService.GetUserById(id);
            String date2String = DateUtils.parseDate2String(userById.getBirthday(),"yyyy-MM-dd");
            userById.setBirthday(DateUtils.parseString2Date(date2String,"yyyy-MM-dd"));
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_USER_FAIL);
        }
        return new Result(true,MessageConstant.QUERY_USER_SUCCESS,userById);
    }


    @PreAuthorize("hasAuthority('USER_QUERY')")
    @RequestMapping("/User/Page")
    public PageResult getUserPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult = null;
        try {
            pageResult = userService.getUserPage(queryPageBean);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageResult;
    }
    
    
    

    //获得当前登录用户的用户名
    @RequestMapping("/User/Username")
    public Result getUserName() {
        //当spring security 完成认证后，会将当前用户信息保存到框架提供的上下文对象中
        User user = null;
        try {
            user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
        System.out.println(user);
        return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, user.getUsername());
    }
    
    @GetMapping("/User/RoleList")
    public Result getRoleList(){
        List<Role> roleList = null;
        try {
            roleList = userService.getRoleList();
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_ROLE_LIST_FAIL);
        }    
        return new Result(true,MessageConstant.GET_ROLE_LIST_SUCCESS,roleList);
    }
    
    @GetMapping("/User/Role/{id}")
    public Result RoleNumByUId(@PathVariable int id){
        List<Integer> roleNumByUId = null;
        try {
            roleNumByUId = userService.RoleNumByUId(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ROLE_FAIL);
        }
        return new Result(true, MessageConstant.QUERY_ROLE_SUCCESS, roleNumByUId);
    }
    
    @PreAuthorize("hasAuthority('USER_DELETE')")
    @DeleteMapping("/User/{id}")
    public Result DeleteUserById(@PathVariable int id){
        try {
            userService.DeleteUserById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_USER_FAIL);
        }
        return new Result(true,MessageConstant.DELETE_USER_SUCCESS);
    }
    
}
